package org.tea.springdata.mina.handler;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.springframework.stereotype.Component;

/**
 * @author: John zhang
 * @version: 0.1
 */
@Component
public class ServerHandler extends IoHandlerAdapter {

	// 当一个客端端连结进入时
	private static final Log log = LogFactory.getLog(ServerHandler.class);

	public void sessionOpened(IoSession session) throws Exception {
		log.info("server  : " + session.getRemoteAddress());
	}

	// 当一个客户端关闭时
	public void sessionClosed(IoSession session) {
		log.info("one server  Disconnect !");
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		if( message instanceof String ) {
			String receivedMsg = (String) message;
			if ("quit".equalsIgnoreCase(receivedMsg)) {
				System.out.println("Session closed");
				session.close(true);
			}
			System.out.println("Client send message is : " + receivedMsg);
			
			receivedMsg = "Server response :" + receivedMsg;
			
			System.out.println("Successfully response to " + session.getRemoteAddress().toString());
			WriteFuture future = session.write(receivedMsg);
			// future.awaitUninterruptibly();
		} else if( message instanceof IoBuffer ) {
			IoBuffer buffer = (IoBuffer) message;
		}
		
		System.out.println("Receive client attribute of publicKey is : " + session.getAttribute("publicKey"));
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		session.close(true);
	}

	// 创建 session
	public void sessionCreated(IoSession session) {

	}
}